"""
高频做市策略
策略逻辑：
1. 实时获取买卖盘口数据
2. 计算中间价和价差
3. 在中间价两侧挂限价单
4. 动态调整报价价差和挂单量
"""

import numpy as np
import pandas as pd

class MarketMakingStrategy:
    def __init__(self, symbol, initial_capital=1000000):
        self.symbol = symbol
        self.capital = initial_capital
        self.position = 0
        self.bid_price = 0
        self.ask_price = 0
        self.spread = 0.001  # 初始价差(0.1%)
        self.order_size = 100  # 初始挂单量
        
    def on_market_data(self, market_data):
        """
        处理市场数据
        """
        # 获取最新盘口
        best_bid = market_data['bid'][0]
        best_ask = market_data['ask'][0]
        mid_price = (best_bid + best_ask) / 2
        
        # 计算动态价差(波动率调整)
        volatility = self.calculate_volatility(market_data)
        self.spread = max(0.0005, volatility * 0.5)  # 价差至少0.05%
        
        # 计算挂单价格
        self.bid_price = mid_price * (1 - self.spread)
        self.ask_price = mid_price * (1 + self.spread)
        
        # 调整挂单量(根据库存风险)
        inventory_risk = abs(self.position) / 1000
        self.order_size = int(100 / (1 + inventory_risk))
        
        return {
            'bid_price': self.bid_price,
            'bid_size': self.order_size,
            'ask_price': self.ask_price, 
            'ask_size': self.order_size
        }
    
    def calculate_volatility(self, market_data):
        """
        计算实时波动率
        """
        # 使用过去100个tick计算标准差
        returns = np.diff(np.log(market_data['price'][-100:]))
        return np.std(returns) if len(returns) > 0 else 0.001
    
    def on_order_executed(self, order):
        """
        处理成交回报
        """
        if order['side'] == 'buy':
            self.position += order['filled_qty']
            self.capital -= order['filled_qty'] * order['price']
        else:
            self.position -= order['filled_qty'] 
            self.capital += order['filled_qty'] * order['price']

if __name__ == '__main__':
    # 模拟运行
    strategy = MarketMakingStrategy('BTC-USDT')
    
    # 模拟市场数据
    mock_data = {
        'bid': [50000, 49999, 49998],
        'ask': [50001, 50002, 50003],
        'price': [50000, 50001, 50002, 50001, 50000]
    }
    
    # 生成报价
    quotes = strategy.on_market_data(mock_data)
    print("做市报价:", quotes)